import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.Date;
import java.lang.System;

/**
 * Java program to create a simple HTTP Server to demonstrate how to use
 * ServerSocket and Socket class.
 * 
 * @author Javin Paul
 */
public class SimpleHTTPServer {

  public static void main(String[] args) throws IOException {
      int port = 8080;
      HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
      HttpContext context = server.createContext("/");
      context.setHandler(SimpleHTTPServer::handleRequest);
      System.out.printf("HTTP server listening on port %d...\n", port);
      server.start();
  }

  private static void handleRequest(HttpExchange exchange) throws IOException {
      Date today = new Date();
      String response = "Hi there!\n\n" + today;
      exchange.sendResponseHeaders(200, response.getBytes().length);//response code and length
      OutputStream os = exchange.getResponseBody();
      os.write(response.getBytes());
      os.close();
  }

}